﻿using ERPNextAuthentication.Configs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ERPNextAuthentication
{
    public class Authentication
    {
        public static async Task<string> GetUserByTokenFile(string tokenFile)
        {
            string user = null;

            try
            {
                using (FileStream fs = new FileStream(tokenFile, FileMode.Open, FileAccess.Read))
                {
                    StreamReader streamReader = new StreamReader(fs);
                    string api_key_pair = streamReader.ReadToEnd();


                    //token方式验证
                    using (var client = new HttpClient())
                    {
                        // 设置请求的 URI。
                        var requestUri = $"http://{AuthConfig.Current.ServerUrl}/api/method/frappe.auth.get_logged_user";

                        // 创建HttpRequestMessage
                        using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
                        {
                            request.Headers.Add("Authorization", $"token {api_key_pair}");

                            // 发送请求
                            using (var response = await client.SendAsync(request))
                            {
                                response.EnsureSuccessStatusCode();
                                string responseBody = await response.Content.ReadAsStringAsync();

                                // 处理响应
                                //{"message":"nqs3ghb@dingtalk.com"}
                                Console.WriteLine(responseBody);
                                var obj=JsonConvert.DeserializeObject<Dictionary<string,string>>(responseBody);
                                var userid = obj["message"];
                                user=Database.ERPNext.ERPNextDbContext.Current.tabUsers.Where(x=>x.name==userid).Select(x=>x.full_name).FirstOrDefault();

                            }
                        }
                    }
                }
            }
            catch(Exception ex) {
                Serilog.Log.Error($"【系统】登录失败：{ex.Message}");
                user = null;
            }


            
            return user;
        }

        public static async Task<string> GetUserByPassword(string usr,string password)
        {
            string user = null;
            try
            {
                //密码方式验证
                using (var client = new HttpClient())
                {
                    // 设置请求的 URI。
                    var url = $"http://{AuthConfig.Current.ServerUrl}/api/method/login";

                    // 创建HttpRequestMessage
                    using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        // 添加自定义header


                        request.Headers.Add("Accept", "application/json");
                        //request.Headers.Add("Content-Type", "application/json");

                        //var json = "{\"usr\":\"test@test.com\",\"pwd\":\"Test@123456\"}";
                        string json = $"{{\"usr\":\"{usr}\",\"pwd\":\"{password}\"}}";//
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        request.Content = content;

                        // 发送请求
                        using (var response = await client.SendAsync(request))
                        {
                            response.EnsureSuccessStatusCode();
                            string responseBody = await response.Content.ReadAsStringAsync();

                            // 处理响应
                            //{"message":"Logged In","home_page":"/app","full_name":"test"}
                            //{"message":"Logged In","home_page":"/app","full_name":"\u91d1\u5170"}
                            Console.WriteLine(responseBody);
                            var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);
                            user= obj["full_name"];
                        }
                    }
                }




            }
            catch (Exception ex)
            {
                Serilog.Log.Error($"【系统】登录失败：{ex.Message}");
                user = null;
            }
            return user;
        }
    }
}
